package com.example.woke;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bean.BankAccountAndPayChannel;
import com.bean.BaseResponse;
import com.http.HttpMethods;
import com.jakewharton.rxbinding2.view.RxView;
import com.woke.adapter.UnionPayChannelAdapter;
import com.woke.data.Datas_bankedcard;
import com.woke.data.Datas_chongzhi;
import com.woke.data.Datas_nocardback;
import com.woke.data.Datas_paytype;
import com.woke.data.UnionPayChannel;
import com.woke.diyview.Alertdialogall;
import com.woke.method.Httpgetbank;
import com.woke.method.Httpgetorderid;
import com.woke.method.Httpgetpaytype;
import com.woke.method.Httploaddata;
import com.woke.method.MyApp;
import com.woke.serizedatas.Datas_load;
import com.zhongcai.online.R;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

public class ChongzhiActivity extends Activity implements OnClickListener {

    private static final int REQUEST_BIND_CARD = 9;//绑卡请求
    private static final int REQUEST_AUTH_PAY_PASSWORD = 19;//支付密码验证
    private TextView mTbankname, mTcarno;
    private Button mSureBtn;
    private EditText mEmoney;
    private MyApp application;
    private ArrayList<Datas_bankedcard> mBankedCards = new ArrayList<Datas_bankedcard>();
    private String order_id, playform;
    private RelativeLayout mRelative;
    private boolean showed;
    private float transAmount;// ���׽��

    private LayoutInflater inflater;
    private RelativeLayout mFrame, mFrame1;
    private String cardno;//Ҫ��ֵ�����տ���
    private String title;//���ʽ
    private RecyclerView mChannelRecyView;
    private UnionPayChannelAdapter mChannelAdapter;
    private ArrayList<UnionPayChannel> mUnionPayChannels = new ArrayList<>();

    private Alertdialogall mSettingPayPaw = new Alertdialogall();

    AlertDialog bindardAd;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chongzhi);
        EventBus.getDefault().register(this);
        application = (MyApp) getApplication();
        intview();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);

    }

    private void intview() {
        inflater = getLayoutInflater();
        mTbankname = (TextView) findViewById(R.id.avczhi_text_bankname);
        mTcarno = (TextView) findViewById(R.id.avczhi_text_cardno);
        mSureBtn = (Button) findViewById(R.id.avczhi_text_next);
        RxView.clicks(mSureBtn)
                .throttleFirst(2, TimeUnit.SECONDS)
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        //防抖动,避免多次操作
                        goToNocardPay();
                    }
                });
//		mTnext.setOnClickListener (this);
        mEmoney = (EditText) findViewById(R.id.avczhi_edit_money);//���
        mEmoney.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String temp = s.toString();
                if (!TextUtils.isEmpty(temp)) {

                    int posDot = temp.indexOf(".");
                    if (posDot <= 0) return;
                    if (temp.length() - 1 - posDot > 2) {
                        s.delete(posDot + 3, posDot + 4);
                    }
                }
            }
        });
        mRelative = (RelativeLayout) findViewById(R.id.avczhi_relatie_morebank);//�а�ʱ
        mRelative.setOnClickListener(this);
        mFrame = (RelativeLayout) findViewById(R.id.avchongzhi_frame);//�ս���ʱ��ʾ
        mFrame1 = (RelativeLayout) findViewById(R.id.avchongzhi_frame1);//����ת��ʾ
        findViewById(R.id.avczhi_image_back).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        mChannelRecyView = (RecyclerView) findViewById(R.id.channel_recyclerView);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        layoutManager.setSmoothScrollbarEnabled(true);
        layoutManager.setAutoMeasureEnabled(true);
        mChannelRecyView.setLayoutManager(layoutManager);
        mChannelRecyView.setHasFixedSize(true);
        mChannelRecyView.setNestedScrollingEnabled(false);
        mChannelAdapter = new UnionPayChannelAdapter(ChongzhiActivity.this, mUnionPayChannels);
        mChannelRecyView.setAdapter(mChannelAdapter);

//		getbanklist();
//		getpaytype();
        getbanklistAndUnionPayChannel();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (application == null) {
            application = MyApp.getInstance();
        }
        Httploaddata.uploadFile(application);

    }

    /**
     * 获取银行卡列表和渠道
     */
    private void getbanklistAndUnionPayChannel() {
        if (application.getDatas_load() != null) {

            int userid = Integer.parseInt(application.getDatas_load().getId());
            HttpMethods.getInstance()
                    .getBankAccountAndUnionPayChannel(mAccountsAndChannelsObserver, userid, 1, 3);
        }
    }

    private Observer<BankAccountAndPayChannel> mAccountsAndChannelsObserver = new Observer<BankAccountAndPayChannel>() {
        @Override
        public void onSubscribe(Disposable d) {

        }

        @Override
        public void onNext(BankAccountAndPayChannel value) {
            if (value != null) {
                List<Datas_bankedcard> baList = value.getBanklist();
                List<UnionPayChannel> clist = value.getGalllist();
                if (baList != null && baList.size() > 0) {
                    mBankedCards.clear();
                    mBankedCards.addAll(baList);
                }
                if (mBankedCards.size() > 0) {
                    if (showed == false) {
                        Datas_bankedcard data = mBankedCards.get(0);

                        mTbankname.setText(data.getBrname());
                        mRelative.setVisibility(View.VISIBLE);
                        cardno = data.getCardno();
                        mTcarno.setText("尾号" + data.getCardno()
                                .substring(data.getCardno().length() - 4, data.getCardno()
                                        .length()));
//
                    } else {
                        Datas_bankedcard data = mBankedCards.get(mBankedCards.size() - 1);
                        mTbankname.setText(data.getBrname());
                        mRelative.setVisibility(View.VISIBLE);
                        cardno = data.getCardno();
                        mTcarno.setText("尾号" + data.getCardno()
                                .substring(data.getCardno().length() - 4, data.getCardno()
                                        .length()));
                    }
                    mSureBtn.setEnabled(true);

                } else {
//                    Toast.makeText(ChongzhiActivity.this, "请先绑定一张银行号后在支付", Toast.LENGTH_SHORT)
//                            .show();
//                    Intent intent = new Intent(ChongzhiActivity.this, MywalletcardActivity.class);
//                    intent.putExtra("czhiortxian", "no");
//                    startActivityForResult(intent, REQUEST_BIND_CARD);
                    aralogid("还未绑卡","前去绑卡");
                    return;
                }

                if (clist != null && clist.size() > 0) {
                    mUnionPayChannels.clear();
                    mUnionPayChannels.addAll(clist);
                    if (mChannelAdapter != null) {
                        mChannelAdapter.notifyDataSetChanged();
                    }
                }
            }
        }

        @Override
        public void onError(Throwable e) {

            Toast.makeText(ChongzhiActivity.this, e.getMessage(), Toast.LENGTH_SHORT)
                    .show();
        }

        @Override
        public void onComplete() {

        }
    };

    private void getpaytype() {
        String getbanked = Httpgetpaytype.getbanked(mFrame);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(Datas_paytype event) {
        title = event.title;
    }

    private int getwhichcard(String cardnew) {
        int whichcard = -1;
        for (int i = 0; i < mBankedCards.size(); i++) {
            if (cardnew.equals(mBankedCards.get(i).getCardno())) {
                whichcard = i;
            }
        }
        return whichcard;

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(Datas_chongzhi event) {
        order_id = event.getOrder_id();
//		String cardno = mTcarno.getText().toString().trim();
//		Datas_bankedcard list = datalist.get(currentno);
        Datas_bankedcard list1 = mBankedCards.get(getwhichcard(cardno));
        Datas_nocardback nocarback = new Datas_nocardback();
        nocarback.setCardno(list1.getCardno());
        nocarback.setName(list1.getName());
        nocarback.setSfz(list1.getIdcard());
        nocarback.setCardno(list1.getCardno());
        nocarback.setPhone(list1.getPhone());
        nocarback.setBank(list1.getBrname());
        nocarback.setCvv(list1.getCode());
        nocarback.setValidthru(list1.getValidthru());
        nocarback.setCardtype(list1.getType());
        nocarback.setMoney(transAmount);
        nocarback.setId(order_id);
        Intent intent1 = new Intent(ChongzhiActivity.this, NocardpayActivity.class);
        intent1.putExtra("cardlist", nocarback);
        intent1.putExtra("datalist", mBankedCards);
        intent1.putExtra("title", title);
        startActivity(intent1);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(Datas_nocardback event) {
        showed = true;
        getbanklist();
    }

    private void getbanklist() {
        if (application.getDatas_load() != null) {
            Httpgetbank.getbanked(application.getDatas_load().getId(), mFrame);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(ArrayList<Datas_bankedcard> event) {
        mBankedCards.clear();
        mBankedCards.addAll(event);
        if (mBankedCards.size() > 0) {
            if (showed == false) {
                Datas_bankedcard data = mBankedCards.get(0);
                Datas_nocardback nocarback = new Datas_nocardback();
                nocarback.setCardno(data.getCardno());
                nocarback.setBank(data.getBrname());
                nocarback.setCardtype(data.getType());
                mTbankname.setText(data.getBrname());
                mRelative.setVisibility(View.VISIBLE);
                cardno = data.getCardno();
                mTcarno.setText("尾号" + data.getCardno()
                        .substring(data.getCardno().length() - 4, data.getCardno().length()));
            } else {
                Datas_bankedcard data = mBankedCards.get(mBankedCards.size() - 1);
                Datas_nocardback nocarback = new Datas_nocardback();
                nocarback.setCardno(data.getCardno());
                nocarback.setBank(data.getBrname());
                nocarback.setCardtype(data.getType());
                mTbankname.setText(data.getBrname());
                mRelative.setVisibility(View.VISIBLE);
                cardno = data.getCardno();
                mTcarno.setText("尾号" + data.getCardno()
                        .substring(data.getCardno().length() - 4, data.getCardno().length()));
            }
        } else {
//            Toast.makeText(ChongzhiActivity.this, "请先绑定一张银行卡", Toast.LENGTH_SHORT).show();
//            Intent intent = new Intent(ChongzhiActivity.this, MywalletcardActivity.class);
//            intent.putExtra("czhiortxian", "chongzhi");
//            startActivity(intent);
            aralogid("还未绑卡","前去绑卡");
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 91 && resultCode == 93) {
            ArrayList<String> listnew = data.getStringArrayListExtra("chongzhi1");
            mTbankname.setText(listnew.get(4));
            cardno = listnew.get(2);
            mTcarno.setText("尾号" + listnew.get(3)
                    .substring(listnew.get(3).length() - 4, listnew.get(3).length()));
        } else if (requestCode == REQUEST_BIND_CARD) {
            getbanklistAndUnionPayChannel();
        } else if (requestCode == REQUEST_AUTH_PAY_PASSWORD && resultCode == 600) {
            if (data != null) {
                boolean isRight = data.getBooleanExtra("paypsw", false);
                if (isRight) {
                    String money = mEmoney.getText().toString().trim();
                    if (TextUtils.isEmpty(money)) {
                        Toast.makeText(ChongzhiActivity.this, "请输入充值金额", Toast.LENGTH_SHORT)
                                .show();
                        return;
                    }
                    if (mChannelAdapter == null || mChannelAdapter.getWay() == -1) {

                        isBindedToRecharge(Integer.parseInt(application.getDatas_load()
                                .getId()), Float.parseFloat(money), 1, cardno);
                    } else {

                        isBindedToRecharge(Integer.parseInt(application.getDatas_load()
                                .getId()), Float.parseFloat(money), mChannelAdapter.getWay(), cardno);
                    }
                } else {
                    Toast.makeText(ChongzhiActivity.this, "请输入正确支付密码", Toast.LENGTH_SHORT)
                            .show();
                }
            }

        }
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.avczhi_relatie_morebank:
                Intent intent = new Intent(ChongzhiActivity.this, MybankblindActivity.class);
                intent.putExtra("czhiortxian", "chongzhi");
                startActivityForResult(intent, 91);
                break;

            case R.id.avczhi_text_next:
                String trim = "" + mEmoney.getText().toString().trim();
                if (!trim.equals("")) {
                    transAmount = Float.parseFloat(trim);
                }
                if (null == trim || trim.equals("")) {
                    Toast.makeText(ChongzhiActivity.this, "请输入充值金额", Toast.LENGTH_SHORT).show();
                } else {
                    if (application.getDatas_load() != null) {
                        Httpgetorderid.getorderid(application.getDatas_load()
                                .getId(), mFrame1, transAmount);
                    }
                }
                break;

            default:
                break;
        }
    }

    private void isBindedToRecharge(int user_id, float amount, int way, String card_no) {
        SuccessObserver mSuccessObserver = new SuccessObserver(user_id, amount, way, card_no);
        HttpMethods.getInstance()
                .isBindedToRecharge(mSuccessObserver, user_id, amount, way, card_no);

    }

    private class SuccessObserver implements Observer<BaseResponse> {

        private int user_id;
        private float amount;
        private int way;
        private String card_no;

        public SuccessObserver(int user_id, float amount, int way, String card_no) {
            this.user_id = user_id;
            this.amount = amount;
            this.way = way;
            this.card_no = card_no;
        }

        @Override
        public void onSubscribe(Disposable d) {

        }

        @Override
        public void onNext(BaseResponse value) {
            if (value != null) {
                Log.e("onError", value.toString());
                if (value.resultSuccess()) {
                    Toast.makeText(ChongzhiActivity.this, "充值成功", Toast.LENGTH_LONG)
                            .show();
                    new AlertDialog.Builder(ChongzhiActivity.this).setMessage(value.getInfo()).setPositiveButton("完成", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            finish();
                        }
                    });
                } else {
                    Toast.makeText(ChongzhiActivity.this, value.getInfo(), Toast.LENGTH_SHORT)
                            .show();
                }
            }
        }

        @Override
        public void onError(Throwable e) {
            if (e == null) return;
            Log.e("onError", e.getMessage());
            Toast.makeText(ChongzhiActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
            if (e.getMessage().equals("unbind")) {
                //未绑卡
                HttpMethods.getInstance()
                        .bindingBankAccount(mBindingObserver, user_id, 1, card_no);
            } else {
                Toast.makeText(ChongzhiActivity.this, e.getMessage(), Toast.LENGTH_SHORT)
                        .show();
            }
        }

        @Override
        public void onComplete() {

        }
    }

    private Observer<BaseResponse<String>> mBindingObserver = new Observer<BaseResponse<String>>() {


        @Override
        public void onSubscribe(Disposable d) {

        }

        @Override
        public void onNext(BaseResponse<String> value) {
            if (value != null) {
                if (value.resultSuccess()) {
                    Intent intent = new Intent(ChongzhiActivity.this, UnionPayBindActivity.class);
                    intent.putExtra("html", value.getData().getData());
                    startActivity(intent);
                }
            }

        }

        @Override
        public void onError(Throwable e) {
            Toast.makeText(ChongzhiActivity.this, e.getMessage(), Toast.LENGTH_SHORT)
                    .show();
        }

        @Override
        public void onComplete() {

        }
    };

    /**
     * 确认,进行支付判断
     */
    private void goToNocardPay() {
        mSureBtn.setFocusableInTouchMode(true);
        mSureBtn.setFocusable(true);
        mSureBtn.requestFocus();
        String moneyStr = mEmoney.getText().toString().trim();
        if (TextUtils.isEmpty(moneyStr)) {
            Toast.makeText(this, "请输入充值金额", Toast.LENGTH_SHORT).show();
            return;
        }
        if (null == cardno || cardno.equals("")) {
            Toast.makeText(ChongzhiActivity.this, "请选择银行卡", Toast.LENGTH_SHORT)
                    .show();
        } else {
            if (mBankedCards.size() > 0) {
                if (getwhichcard(cardno) == -1) {
//							getcardinfo (cardno);
                } else {
                    Datas_bankedcard list = mBankedCards.get(getwhichcard(cardno));
                    Datas_load datasLoad = application.getDatas_load();

                    if (datasLoad != null) {
                        if (TextUtils.isEmpty(datasLoad.getPay_pwd())) {
                            mSettingPayPaw.aralogid(ChongzhiActivity.this, "还未设置支付密码", "前往设置？");
                        } else {
                            Intent intent1 = new Intent(ChongzhiActivity.this, CheckpaypswActivity.class);
                            intent1.putExtra("paymoney", String.valueOf(moneyStr));
                            intent1.putExtra(CheckpaypswActivity.KEY_PAY_TYPE, "chongzhi");
                            startActivityForResult(intent1, REQUEST_AUTH_PAY_PASSWORD);
                        }
                    }

                }

            }

        }
    }
    private void aralogid(String info, String kll) {
        bindardAd = new AlertDialog.Builder(ChongzhiActivity.this).
                setTitle(info).
                setMessage(kll).
                setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
//                        Intent intent = new Intent();
//                        intent.setClass(ChongzhiActivity.this, LoadActivity.class);
//                        startActivity(intent);
                        Intent intent = new Intent(ChongzhiActivity.this, MywalletcardActivity.class);
                        intent.putExtra("czhiortxian", "no");
                        startActivityForResult(intent, REQUEST_BIND_CARD);
                        bindardAd.dismiss();
                    }
                }).
                setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        bindardAd.dismiss();
                    }
                }).create();
        bindardAd.show();
    }

}
